package cn.imatu.framework.security;

import cn.imatu.framework.cache.redis.config.FastJson2JsonRedisSerializer;
import cn.imatu.framework.tool.crypto.asymmetric.AsymmetricCryptoManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@AutoConfiguration
public class LySecurityAutoConfiguration {
    private static final Logger log = LoggerFactory.getLogger(LySecurityAutoConfiguration.class);

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @PostConstruct
    public void init() {
        log.info("init {}", this.getClass().getName());
    }

    @Bean(name = "asymmetricCryptoManager")
    public AsymmetricCryptoManager asymmetricCryptoManager() {
        return new AsymmetricCryptoManager();
    }

    @Bean(name = "securityRedisTemplate")
    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate<String, Object> securityRedisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setValueSerializer(serializer);
        template.setKeySerializer(new StringRedisSerializer());

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}
